using System.Text;

namespace Crux.Core.Websockets.Metadata;
/// <summary>
/// Message
/// </summary>
public class Message : IDisposableObservable
{
    /// <summary>
    ///
    /// </summary>
    [JsonProperty("type")]
    public MessageType Type { get; set; }
    /// <summary>
    /// 
    /// </summary>
    public bool IsDisposed { get; private set; }

    private byte[]? buffer;
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    /// <exception cref="ObjectDisposedException"></exception>
    public byte[] GetBuffer()
    {
        if (IsDisposed)
        {
            throw new ObjectDisposedException("MessageDisposed");
        }

        if (buffer is not null)
        {
            return buffer;
        }

        var json = JsonExtensions.JsonStringify(this);

        return buffer = Encoding.UTF8.GetBytes(json);
    }
    /// <summary>
    /// 
    /// </summary>
    public void Dispose()
    {
        if (IsDisposed)
        {
            return;
        }

        IsDisposed = true;

        if (buffer is not null)
        {
            Array.Clear(buffer, 0, buffer.Length);
            buffer = null;
        }
    }
}